// mongodb
var cfg = require('../cfg/cfg.js')
// var Db = require('mongodb').Db
// var Connection = require('mongodb').Connection
// var Server = require('mongodb').Server
var MongoClient = require('mongodb').MongoClient;

var mongodb = {}
module.exports = mongodb
mongodb.pool={};
var dbs=[];
var url='mongodb://'+cfg.dbAddr+'/'+cfg.db;
console.log(url)
mongodb.get=function(cb){
	MongoClient.connect(url,{useUnifiedTopology: true, useNewUrlParser: true},function(err, db) {
		if(db!=null)
		{
	        dbs.push(db);
	        cb(null,db);
		}else{
			cb(err,null)
		}
	});
};

mongodb.release=function(db){
	for(var i=0;i<dbs.length;i++)
	{
		if(dbs[i]==db)
		{
			dbs.splice(i,1);
			break;
		}
	}
	db.close();
};

mongodb.gc = function() {
	var tick=(new Date()).getTime();
	for(var i=0;i<dbs.length;i++)
	{
		var db=dbs[i];
		if(tick-db._bornTick>600000)
		{
			dbs.splice(i,1);
			db.close();
			return;
		}
	}
}